package com.xh.xyzp.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.xh.xyzp.common.constant.UserContext;
import com.xh.xyzp.domain.entity.User;
import com.xh.xyzp.exception.ApiException;
import com.xh.xyzp.util.RedisUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Author: xianghao
 * @Description:
 * @Date: 2024-10-01  19:11
 */
@Component("tokenInterceptor")
public class TokenInterceptor implements HandlerInterceptor {

    // 白名单路径
    private String[] urls = new String[]{
            "/api/user/login", "/api/user/register",
            "/api/job/list", "/api/job/type/list",
            "/api/oss/download/**", "/api/email/send/**", "/api/notice/list"
    };

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String token = request.getHeader("token");
        PathMatcher pathMatcher = new AntPathMatcher();
        for (String url : urls) {
            if (pathMatcher.match(url, requestURI)){
                if (StrUtil.isEmpty(token)){
                    return true;
                }
                break;
            }
        }

        if (StrUtil.isEmpty(token)){
            throw new ApiException("需要身份验证");
        }
        User user = parseTokenToUser(token);
        if (Objects.isNull(user)){
            throw new ApiException("身份验证失败");
        }
        UserContext.setUser(user);

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    public static User parseTokenToUser(String token) {
        String userStr = RedisUtil.get(token);
        if (StrUtil.isEmpty(userStr)) {
            throw new ApiException("身份过期，请重新登录");
        }
        return JSONUtil.toBean(userStr, User.class);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
